<?php

namespace Beerus\Modules\DecoCompany\Actions;

use Doraemon\model\DecoCompany\DecoCompanyOperatorBind;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\service\DecoCompany\AdminOperator;
use Illuminate\Http\Request;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;

class BindOperator extends RowAction {
    public $name = '认领';

    public function handle($id) {
        // 获取用户uid
        $uid = DecoCompanyAuth::get('uid', ['id' => $id]);
        if (empty($uid)) {
            return $this->response()->error('未找到该装修公司');
        }
        $adminName = Admin::user()->username;
        $model = DecoCompanyOperatorBind::get('*', ['uid' => $uid, 'admin_name' => $adminName]);
        if(!$model || $model['data_status'] == DecoCompanyOperatorBind::STATUS_DELETE) {
            $res = AdminOperator::bind($uid, $adminName);
            if($res == AdminOperator::STATUS_SUCCESS) {
                return $this->response()->success('认领成功')->refresh();
            } else if($res == AdminOperator::STATUS_REPEAT) {
                return $this->response()->success('已经认领,不需要重复操作');
            } else if($res == AdminOperator::STATUS_FAIL_BEBIND) {
                return $this->response()->error('认领失败，已被其他运营人员认领');
            } else if ($res == AdminOperator::STATUS_FAIL_CANT_BIND) {
                return $this->response()->error('认领失败，只有固定运营人员才可以认领');
            } else {
                return $this->response()->error('失败');
            }
        } else {
            return $this->response()->error('未找到该记录');
        }
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }
}
